package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            //2处理请求
            String path = request.getUri();
            File root = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(root,"static");
            File file = new File(staticDir,path);

            println("HTTP/1.1 200 OK");
            println("Content-Type: text/html");
            println("Content-length"+file.length());
            println("");

            //3发送响应
            OutputStream out = socket.getOutputStream();
            int len;
            byte[] data = new byte[1024*10];
            FileInputStream fis = new FileInputStream(file);
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
            System.out.println("响应发送完毕!!!!");

        }catch (IOException | URISyntaxException e){
            e.printStackTrace();
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }

}
